﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Common;

public partial class Setting_UserEdit : PageBase
{
    public string PageTitle = "";
    public string strdivreadonlystyle = " ms-crm-ReadOnly ms-crm-Lookup-ReadOnly", strimgreadonlystyle = "disabled";
    protected string navbar = "<li class=\"ms-crm-Tab\" id=\"tab1Tab\" tabindex=\"-1\" tabid=\"tab1\"><a onclick=\"return false;\" href=\"javascript:onclick();\" target=\"_self\">用户组</a></li>";

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin("system user");

        ///保存
        if (RequestBase.GetFormString("__EVENTTARGET") == "save")
        {
            SaveInfo();
        }

        if (!IsPostBack)
        {
            RolesListDataBind();

            if (RequestBase.GetQueryString("otype") == "modify")
            {
                PageTitle = "修改";
                spanRoleName.InnerText = "修改用户设置";
                Initialize();
            }
            else
            {
                navbar = "";
                PageTitle = "添加";
                spanRoleName.InnerText = "添加用户";
            }
        }
    }

    #region 角色
    void RolesListDataBind()
    {
        DataTable dat = new DataTable();

        if (RequestBase.GetQueryString("") != "")
        {
            if (!Validate("group settings", 1))
                dat = BLL.CommonBLL.Select("System_Roles", "*", " AND IsProtected = 0 AND RoleId IN (SELECT RoleId FROM System_UsersInRoles WHERE SystemUserId = '" + RequestBase.GetQueryString("userid") + "') AND IsLockout = 0  ORDER BY LineNum ASC, LoweredRoleName ASC");
            else
                dat = BLL.CommonBLL.Select("System_Roles", "*", " AND RoleId IN (SELECT RoleId FROM System_UsersInRoles WHERE SystemUserId = '" + RequestBase.GetQueryString("userid") + "') AND IsLockout = 0  ORDER BY LineNum ASC, LoweredRoleName ASC");
        }
        else
        {
            if (!Validate("group settings", 1))
                dat = BLL.CommonBLL.Select("System_Roles", "*", " AND IsProtected = 0 AND IsLockout = 0  ORDER BY LineNum ASC, LoweredRoleName ASC");
            else
                dat = BLL.CommonBLL.Select("System_Roles", "*", " AND IsLockout = 0  ORDER BY LineNum ASC, LoweredRoleName ASC");
        }

        foreach (DataRow dr in dat.Select())
        {
            cbxRolesList.Items.Add(new ListItem(dr["RoleName"].ToString(), dr["RoleId"].ToString()));
        }
    }
    #endregion

    #region 信息初始化
    void Initialize()
    {
        GetObj = BLL.SystemUserBase.GetObjById(RequestBase.GetQueryString("userid"));
    }

    ///// <summary>
    ///// 信息实体
    ///// </summary>
    Model.SystemUserBase GetObj
    {
        get
        {
            Model.SystemUserBase _users = new Model.SystemUserBase();

            if (!string.IsNullOrEmpty(RequestBase.GetQueryString("userid").Trim()))
            {
                _users.SystemUserId = RequestBase.GetQueryString("userid").Trim();
            }
            _users.Username = txtUsername.Value.Trim();
            _users.FullName = txtFullName.Value.Trim(); 
            _users.NickName = txtNickName.Value.Trim();
            _users.BusinessUnitId = txtBusinessUnitId.Value.Trim();

            if (txtPassword.Value.Trim() == "")
            {
                _users.Password = "";
            }
            else
            {
                _users.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Value.Trim(), "md5");
            }

            _users.InternalEmail = txtInternalEmailAddress.Value;
            _users.Comment = "";
            _users.CreatedBy = this.SystemUserId;
            _users.CreatedOn = DateTime.Now;

            return _users;
        }
        set
        {
            if (value != null)
            {
                txtUsername.Value = value.Username;
                txtFullName.Value = value.FullName;
                txtPassword.Value = value.Password;
                txtInternalEmailAddress.Value = value.InternalEmail;  
                txtNickName.Value = value.NickName;
                txtRolesId.Value = value.RolesId;

                foreach (string roleid in value.RolesId.Split('|'))
                {
                    foreach (ListItem _item in cbxRolesList.Items)
                    {
                        if (_item.Value == roleid)
                            _item.Selected = true;
                    }
                } 
            }
        }
    }
    #endregion

    void SaveInfo()
    {
        string res = "";

        if (RequestBase.GetQueryString("otype").Trim() == "add")
        {
            if (!Validate("system user", 1))
            {
                JScript.Alert("You have not permissions to add new a user, to the operation failed.");
                return;
            }

            if (txtPassword.Value.Trim() == "")
                txtPassword.Value = "12345678";

            res = BLL.SystemUserBase.Add(GetObj);
        }

        if (RequestBase.GetQueryString("otype").Trim() == "modify")
        {
            if (!Validate("system user", 2))
            {
                JScript.Alert("You have not permissions to modify user info, to the operation failed");
                return;
            }
            res = BLL.SystemUserBase.Update(GetObj);
        }

        switch (res.Split('|')[0])
        {
            case "succeeded":
                string arrroles = "";
   
                foreach (ListItem _item in cbxRolesList.Items)
                {
                    if (txtRolesId.Value.Trim().IndexOf(_item.Value.Trim(), 0) >= 0)
                        BLL.SystemRoles.RemoveUsersFromRoles(res.Split('|')[1].Trim(), _item.Value.ToLower().Trim());

                    if (_item.Selected)
                        arrroles += _item.Value.Trim() + ",";
                }
                if (arrroles != "")
                {
                    arrroles += "|";
                    arrroles = arrroles.Replace(",|", "");

                    res = BLL.SystemRoles.AddUserToRoles(res.Split('|')[1].Trim(), arrroles);
                }

                if (RequestBase.GetQueryString("otype") == "modify")
                {
                    JScript.AlertAndReturnValueToParent("Information saved successfully!", "window.dialogArguments.document.getElementById(\"RefreshItems\").click(); window.close();");
                }
                else
                {
                    JScript.AlertAndReturnValueToParent("Information saved successfully!", "window.dialogArguments.document.getElementById(\"RefreshItems\").click(); window.close();");
                }
                break;
            case "用户名已存在!":
                JScript.Alert("The username has exists!");
                break;
            default:
                JScript.Alert("The operation failed!");
                break;
        }
    }
}
